package com.statistics.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Studio on 2017/1/6.
 * author fj
 */
public class HttpClient {

	private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);

	//post 请求
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			//打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			//设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			connection.setRequestProperty("Cache-Control", "no-cache");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			//发送POST请求必须设置如下两行
			connection.setDoOutput(true);
			connection.setDoInput(true);
			//获取URLConnection对象对应的输出流
			out = new PrintWriter(connection.getOutputStream());
			//发送请求参数
			out.print(param);
			//flush输出流的缓冲
			out.flush();
			//定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(connection.getInputStream(), "utf-8"));//全文编码保持一致
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			//System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
//            logger.debug("HttpClient:sendPost:exception{}" + e.toString());
		}
		//使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
//                logger.debug("HttpClient:sendPost:exception{}" + ex.toString());
			}
		}
		return result;
	}

	public static String sendJson(String ADD_URL, String JSON, Map<String, String> propertys) {
		BufferedReader in ;
		try {
			//创建连接
			URL url = new URL(ADD_URL);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type",
					"application/json; charset=utf-8");
			connection.setRequestProperty("Cache-Control", "no-cache");
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			if(propertys !=null){
				for (String key : propertys.keySet()) {
					connection.addRequestProperty(key, propertys.get(key));
				}
			}
			connection.connect();

			//POST请求
			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());
			out.writeBytes(JSON);
			out.flush();
			out.close();

			int code = connection.getResponseCode();
			//读取响应
			if (code != 200 && code != 201) {
				in = new BufferedReader(new InputStreamReader(
						connection.getErrorStream(),"utf-8"));
			}else{
				in = new BufferedReader(new InputStreamReader(
						connection.getInputStream(),"utf-8"));
			}
			String lines;
			StringBuilder sb = new StringBuilder("");
			while ((lines = in.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			in.close();
			// 断开连接
			connection.disconnect();
			return sb.toString();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String HashMap2String(HashMap<String, String> param) {
		String tmp = "";
		Iterator iter = param.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey();
			String val = (String) entry.getValue();

			tmp += key + "=" + val + "&";
		}
		if (tmp != "") {
			tmp = tmp.substring(0, tmp.length() - 1);
		}
		return tmp;
	}
	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param,Map<String,String> propertys) {


			String result = "";
			BufferedReader in = null;
			try {
				String urlNameString = url + "?" + param;
				URL realUrl = new URL(urlNameString);
				// 打开和URL之间的连接
				HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();

				// 设置通用的请求属性
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("Cache-Control", "no-cache");
//				connection.setRequestProperty("user-agent",
//						"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				if(propertys !=null){
					for (String key : propertys.keySet()) {
						connection.addRequestProperty(key, propertys.get(key));
					}
				}
				// 建立实际的连接
				connection.connect();
				int code = connection.getResponseCode();
				if (code != 200 && code != 201) {
					in = new BufferedReader(new InputStreamReader(
							connection.getErrorStream()));
				}else{
					in = new BufferedReader(new InputStreamReader(
							connection.getInputStream()));
				}

				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
			} catch (Exception e) {
				System.out.println("发送GET请求出现异常！" + e);
				e.printStackTrace();
			}
			// 使用finally块来关闭输入流
			finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			return result;
		}
}
